package com.sh.sh_ai_agent.advisor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

import java.util.function.Consumer;

/**
 * 自定义日志顾问
 */
public class MyLoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    private static final Logger logger = LoggerFactory.getLogger(MyLoggerAdvisor.class);

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 0;
    }


    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        before(advisedRequest);
        AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
        after(advisedResponse);
        return advisedResponse;
    }

    private static void after(AdvisedResponse advisedResponse) {
        logger.debug("AI Response: {}", advisedResponse.response().getResult().getOutput().getText());
    }

    private static void before(AdvisedRequest advisedRequest) {
        logger.info("AI Request: {}", advisedRequest.userText());
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        logger.debug("aroundStream BEFORE: {}", advisedRequest);
        Flux<AdvisedResponse> advisedResponses = chain.nextAroundStream(advisedRequest);
        return new MessageAggregator().aggregateAdvisedResponse(advisedResponses, new Consumer<AdvisedResponse>() {
                    @Override
                    public void accept(AdvisedResponse advisedResponse) {
                        logger.debug("aroundStream AFTER: {}", advisedResponse);
                    }
                }
        );
    }
}
